class ApplicationController < ActionController::Base
  
  require 'wannabe_bool'
  require 'will_paginate/array'
  include Pundit
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  protect_from_forgery with: :exception
  include SessionsHelper



  @@mysql_client = nil;

  def json_to_hash(json)
    ActiveSupport::JSON.decode(json)	
  end

  def get_finance_yml
    YAML.load_file("#{Rails.root.to_s}/config/locales/enumerize/finance.zh-CN.yml")
  end

  # 获取授课对象配置,kevin
  def get_teaching_object_yml
    YAML.load_file("#{Rails.root.to_s}/config/settings/yundiudiu_base_config.yml")
  end

  # 页面配置行数
  def get_per_page_num
    return get_teaching_object_yml["per_page_num"];
  end
  

  # 根据当前时间，获取之前30天日期,kevin
  def get_month_days_by_today

    time = Time.new();
    past_days_array = Array.new();
    # 30天日期计算
    day_num = 30;
    for day in 1..29
        past_day = time - 3600 * 24 * (day_num - day);
        past_days_array.push(past_day.strftime("%Y-%m-%d"));
    end
    past_days_array.push(time.strftime("%Y-%m-%d"));
    return past_days_array;
  end

  # 链接数据库,kevin
  def get_mysql_client
    begin
        if @@mysql_client == nil

          mysql_config = YAML.load_file('config/database.yml')
          current_env_config = mysql_config[Rails.env]
          @@mysql_client = Mysql2::Client.new(current_env_config)
        end
        p "获取数据库连接 #{@@mysql_client}"
        return @@mysql_client; 
    rescue Exception => e
        p "ruby conneting mysql errors,kevin"
        @@mysql_client.close;
        @@mysql_client = nil;
    end
  end

  private

  def user_not_authorized(exception)
    Rails.logger.info "当前权限验证失败！"
    policy_name = exception.policy.class.to_s.underscore
    flash[:alert] = t("#{policy_name}.#{exception.query}", scope: "pundit", default: :default)
    redirect_to authoriz_failed_admin_sessions_path

  end
end

